package com.nwpu.server.authserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.nwpu.server.authserver.dao.UserDao;
import com.nwpu.server.authserver.entity.UserEntity;
import com.nwpu.server.authserver.exception.EmailException;
import com.nwpu.server.authserver.exception.UsernameException;
import com.nwpu.server.authserver.service.UserService;
import com.nwpu.server.authserver.vo.LoginForm;
import com.nwpu.server.authserver.vo.PasswordForm;
import com.nwpu.server.authserver.vo.RegisterForm;
import com.nwpu.server.common.response.HttpUtils;
import com.nwpu.server.common.response.PageUtils;
import com.nwpu.server.common.response.Query;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Autowired
    UserDao userDao;

    @Autowired
    UserService userService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public UserEntity queryByUserName(String username) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        UserEntity one = userService.getOne(wrapper);
        System.out.println(one);
        return one;
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        UserEntity userEntity = new UserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new QueryWrapper<UserEntity>().eq("user_id", userId).eq("password", password));
    }

    @Override
    public void register(RegisterForm vo) {
        UserEntity userEntity = new UserEntity();

        //设置其它的默认信息
        //检查用户名和手机号是否唯一。感知异常，异常机制
        checkEmailUnique(vo.getEmail());
        checkUserNameUnique(vo.getUsername());
        userEntity.setUsername(vo.getUsername());

        //密码进行MD5加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());
        userEntity.setPassword(encode);
        userEntity.setEmail(vo.getEmail());
        userEntity.setMobile(vo.getPhone());
        userEntity.setCreateTime(new Date());
        userEntity.setStatus(1);

        //保存数据
        this.baseMapper.insert(userEntity);
    }

    @Override
    public void checkEmailUnique(String email) throws EmailException {

        Integer phoneCount = this.baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("email", email));

        if (phoneCount > 0) {
            throw new EmailException();
        }

    }

    @Override
    public void checkUserNameUnique(String userName) throws UsernameException {

        Integer usernameCount = this.baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("username", userName));

        if (usernameCount > 0) {
            throw new UsernameException();
        }
    }

    @Override
    public UserEntity login(LoginForm vo) {

        String loginacct = vo.getUsername();
        String password = vo.getPassword();

        //1、去数据库查询 SELECT * FROM ums_user WHERE username = ? OR mobile = ?
        UserEntity userEntity = this.baseMapper.selectOne(new QueryWrapper<UserEntity>()
                .eq("username", loginacct).or().eq("mobile", loginacct));

        if (userEntity == null) {
            //登录失败
            return null;
        } else {
            //获取到数据库里的password
            String password1 = userEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //进行密码匹配
            boolean matches = passwordEncoder.matches(password, password1);
            if (matches) {
                //登录成功
                return userEntity;
            }
        }

        return null;
    }


}